from flask import Flask, request, jsonify, send_from_directory, render_template_string
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def get_client_ip():
    if request.headers.get('X-Forwarded-For'):
        return request.headers.get('X-Forwarded-For').split(',')[0].strip()
    return request.remote_addr

@app.route('/upload', methods=['POST'])
def upload_file():
    client_ip = get_client_ip()
    client_folder = os.path.join(UPLOAD_FOLDER, client_ip)
    os.makedirs(client_folder, exist_ok=True)

    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 根据文件扩展名创建子文件夹
    file_extension = os.path.splitext(file.filename)[1][1:].lower()
    extension_folder = os.path.join(client_folder, file_extension)
    os.makedirs(extension_folder, exist_ok=True)

    file_path = os.path.join(extension_folder, file.filename)
    file.save(file_path)
    return jsonify({"status": "File uploaded successfully", "path": file_path}), 200

@app.route('/clients', methods=['GET'])
def list_clients():
    clients = [d for d in os.listdir(UPLOAD_FOLDER) if os.path.isdir(os.path.join(UPLOAD_FOLDER, d))]
    return jsonify(clients)

@app.route('/files/<client_ip>', methods=['GET'])
def list_files(client_ip):
    client_folder = os.path.join(UPLOAD_FOLDER, client_ip)
    if not os.path.exists(client_folder):
        return jsonify({"error": "No files found for this client"}), 404
    
    # 获取扩展名文件夹及其内容
    file_structure = {}
    for root, dirs, files in os.walk(client_folder):
        relative_path = os.path.relpath(root, client_folder)
        file_structure[relative_path] = files
    return jsonify(file_structure)

@app.route('/download/<client_ip>/<path:filename>', methods=['GET'])
def download_file(client_ip, filename):
    client_folder = os.path.join(UPLOAD_FOLDER, client_ip)
    return send_from_directory(client_folder, filename, as_attachment=True)

@app.route('/')
def index():
    return render_template_string(index_html)

index_html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload and Download</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 50px; }
        form { margin-bottom: 30px; }
        .hidden { display: none; }
    </style>
</head>
<body>
    <h1>Upload File</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" required>
        <button type="submit">Upload</button>
    </form>
    <h1>Clients</h1>
    <div id="client-list"></div>
    <h1 class="hidden" id="files-header">Files</h1>
    <div id="file-list" class="hidden"></div>
    <script>
        async function fetchClients() {
            const response = await fetch('/clients');
            if (response.ok) {
                const clients = await response.json();
                const clientListDiv = document.getElementById('client-list');
                clientListDiv.innerHTML = clients.map(client => `
                    <div>
                        <a href="#" onclick="fetchFiles('${client}')">${client}</a>
                    </div>
                `).join('');
            } else {
                document.getElementById('client-list').innerHTML = '<p>No clients found.</p>';
            }
        }
        async function fetchFiles(clientIp) {
            const response = await fetch(`/files/${clientIp}`);
            if (response.ok) {
                const fileStructure = await response.json();
                const fileListDiv = document.getElementById('file-list');
                document.getElementById('files-header').classList.remove('hidden');
                fileListDiv.classList.remove('hidden');
                fileListDiv.innerHTML = Object.keys(fileStructure).map(folder => `
                    <div>
                        <h3>${folder}</h3>
                        ${fileStructure[folder].map(file => `
                            <div>
                                <a href="/download/${clientIp}/${folder}/${file}">${file}</a>
                            </div>
                        `).join('')}
                    </div>
                `).join('');
            } else {
                document.getElementById('file-list').innerHTML = '<p>No files found for this client.</p>';
            }
        }
        fetchClients();
    </script>
</body>
</html>
"""

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)
